package top.omooo.admin.myasynctask;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by Omooo on 2017/8/9.
*/
public class ImageTest extends Activity {
private ImageView imageView;
private ProgressBar progressBar;
private static String URL="http://img.my.csdn.net/uploads/201504/12/1428806103_9476.png";
//
// public ImageTest(ImageView imageView) {
// this.imageView = imageView;
// }
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
imageView = findViewById(R.id.imageView1);
progressBar = findViewById(R.id.progressBar1);
//设置传递进去的参数
new MyAsyncTask().execute(URL);
}
class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
//做初始化操作
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
//操作UI
progressBar.setVisibility(View.GONE);
imageView.setImageBitmap(bitmap);
}
@Override
protected Bitmap doInBackground(String... stings) {
//可变长数组获取传递进来的参数
String url=stings[0];
Bitmap bitmap = null;
URLConnection connection;
InputStream inputStream;
try {
connection = new URL(url).openConnection();
inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//通过decodeStream解析输入流
bitmap = BitmapFactory.decodeStream(bufferedInputStream);
inputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
}